﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using InfoSvc.Data;
using InfoSvc.Data.WPP;
using System.Text.RegularExpressions;

namespace WPP_Console
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private List<Order[]> orders = new List<Order[]>();
        private List<TabItem> tabs = new List<TabItem>();
        private List<int> tabpages = new List<int>();
        private List<OrderQuery> queries = new List<OrderQuery>();
        private DateGroup[] dates = new DateGroup[5];

        private System.Windows.Controls.DataGrid _focusedDataGrid;
        private CloseableTabItem _focusedTabItem;

        private int tabIndex = 0;
        private int currentPage = 1;
        private OrderQuery currentQuery = new OrderQuery();

        public MainWindow()
        {
            InitializeComponent();
            this.AddHandler(CloseableTabItem.CloseTabEvent, new RoutedEventHandler(this.CloseTab));

            //Initialize the DateGroup Array
            for (int i = 0; i < dates.Length; i++)
            {
                dates[i] = new DateGroup();
                dates[i].DateType = (DateType)i;
            }

            //The active tab and grid
            _focusedDataGrid = OrderDataGrid1;
            _focusedTabItem = StartingTabItem;      

            //Initialize orderQuery
            OrderQuery oq = SimpleSearchOrderQuery();
            queries.Add(oq);
            currentQuery = queries[queries.Count - 1];
            Order[] initOrd = new Order[1];
            initOrd[0] = new Order();
            orders.Add(initOrd);
            _populateDataGrid(initOrd);

            //Clear grid
            _focusedDataGrid.Columns.Clear();
            _focusedDataGrid.Items.Clear();
            orders.Remove(initOrd);

            if (currentPage == 1) PageLeft.IsEnabled = false;

            tabpages.Add(currentPage);
            ExecuteSearch();
        }

        /// <summary>
        /// Close tab event handler
        /// </summary>        
        private void CloseTab(object source, RoutedEventArgs args)
        {
            if (OrderTabControl.Items.Count != 1)
            {
                TabItem tabItem = args.Source as TabItem;
                tabpages.RemoveAt(OrderTabControl.Items.IndexOf(tabItem));
                queries.RemoveAt(OrderTabControl.Items.IndexOf(tabItem));
                if (tabItem != null)
                {
                    System.Windows.Controls.TabControl tabControl = tabItem.Parent as System.Windows.Controls.TabControl;
                    if (tabControl != null)
                        tabControl.Items.Remove(tabItem);
                }
                                
                OrderTabControl.SelectedItem = OrderTabControl.Items[OrderTabControl.Items.Count - 1];
            }
        }

        /// <summary>
        /// Call the order window if a row on the mainWindow is clicked
        /// </summary>       
        private void OrderDataGrid1_MouseDoubleClick (object sender, MouseButtonEventArgs e)
        {
            int row = _focusedDataGrid.SelectedIndex;  
            int selectedOrder;

            if (_focusedDataGrid.SelectedItem == null) return;
            else selectedOrder = _focusedDataGrid.SelectedIndex;

            OrderWindow activeWindow = new OrderWindow(orders[OrderTabControl.Items.IndexOf(_focusedTabItem)][selectedOrder], this);
            activeWindow.Show();
        }
        
        /// <summary>
        /// Call the searchQuery Method on button click
        /// </summary>        
        private void ExecuteSearch_Click(object sender, RoutedEventArgs e)
        {
            ExecuteSearch();
        }

        /// <summary>
        /// Executes the current search options on the current tab
        /// </summary>
        public void ExecuteSearch()
        {
            try
            {
                if (orders.Count > 0) orders.RemoveAt(OrderTabControl.Items.IndexOf(_focusedTabItem));
            }
            catch (ArgumentOutOfRangeException e)
            {                
            }
            SyncDates();
            OrderQuery oq = SimpleSearchOrderQuery();
            for (int i = 0; i < dates.Length; i++)
            {
                dates[i] = new DateGroup();
                dates[i].DateType = (DateType)i;
            }
            queries[OrderTabControl.Items.IndexOf(_focusedTabItem)] = oq;
            currentQuery = queries[queries.Count - 1];
            Order[] ord = null;
            if (oq != null) ord = ServiceClient.GetOrders(oq);
            else return;
            if (ord == null || ord.Length == 0 || ord[0].OrderBillingName == null || ord[0].OrderCreationDate == DateTime.MinValue)
            {
                System.Windows.MessageBox.Show("There are no orders to display.");
                DataGrid dg = (DataGrid)_focusedTabItem.Content;
                dg.Items.Clear();
                return;
            }

            orders.Add(ord);

            _populateDataGrid(ord);

            if (KeywordBox.Text == "") _focusedTabItem.Header = "New Search";
            else _focusedTabItem.Header = KeywordBox.Text;
        }

        /// <summary>
        /// Clears the date pickers
        /// </summary>
        private void ClearDates()
        {
            OrderProcessStartDate.SelectedDate = null;
            OrderProcessEndDate.SelectedDate = null;
            OrderTransactionStartDate.SelectedDate = null;
            OrderTransactionEndDate.SelectedDate = null;
            OrderCreationStartDate.SelectedDate = null;
            OrderCreationEndDate.SelectedDate = null;
            PackagePickUpStartDate.SelectedDate = null;
            PackagePickUpEndDate.SelectedDate = null;
            PackageBoxedStartDate.SelectedDate = null;
            PackageBoxedEndDate.SelectedDate = null;

        }

        /// <summary>
        /// takes the current Order array and uses it to populate the data grid
        /// </summary>
        /// <remarks>
        /// Only call after setting the focused datagrid
        /// </remarks>
        private void _populateDataGrid(Order[] ord)
        {
            _focusedDataGrid.Columns.Clear();
            _focusedDataGrid.Items.Clear();

            if (ord == null)
            {
                MessageBox.Show("There are no orders to display.");
                return;
            }

            foreach (Order od in ord)
            {
                if (od.OrderCompleteDate == DateTime.MinValue) od.OrderCompleteDate = null;
                _focusedDataGrid.Items.Add(new Order() { OrderNumber = od.OrderNumber, OrderShippingName = od.OrderShippingName, OrderBillingName = od.OrderBillingName, OrderTransactionDate = od.OrderTransactionDate, OrderProcessDate = od.OrderProcessDate, OrderCompleteDate = od.OrderCompleteDate });
            }

            DataGridTextColumn col2 = new DataGridTextColumn();
            col2.Binding = new System.Windows.Data.Binding("OrderNumber");
            col2.Header = "ORDER NUMBER";
            col2.Width = new DataGridLength(0.16, DataGridLengthUnitType.Auto);
            DataGridTextColumn col3 = new DataGridTextColumn();
            col3.Binding = new System.Windows.Data.Binding("OrderShippingName");
            col3.Header = "SHIPPING NAME";
            col3.Width = new DataGridLength(0.16, DataGridLengthUnitType.Auto);
            DataGridTextColumn col4 = new DataGridTextColumn();
            col4.Binding = new System.Windows.Data.Binding("OrderBillingName");
            col4.Header = "BILLING NAME";
            col4.Width = new DataGridLength(0.16, DataGridLengthUnitType.Star);
            DataGridTextColumn col5 = new DataGridTextColumn();
            col5.Binding = new System.Windows.Data.Binding("OrderTransactionDate");
            col5.Header = "TRANSACTION DATE";
            col5.Width = new DataGridLength(0.16, DataGridLengthUnitType.Star);
            DataGridTextColumn col6 = new DataGridTextColumn();
            col6.Binding = new System.Windows.Data.Binding("OrderProcessDate");
            col6.Header = "DATE PROCESSED";
            col6.Width = new DataGridLength(0.16, DataGridLengthUnitType.Star);
            DataGridTextColumn col7 = new DataGridTextColumn();
            col7.Binding = new System.Windows.Data.Binding("OrderCompleteDate");
            col7.Header = "DATE PICKED UP";
            col7.Width = new DataGridLength(0.16, DataGridLengthUnitType.Star);

            _focusedDataGrid.Columns.Add(col2);
            _focusedDataGrid.Columns.Add(col3);
            _focusedDataGrid.Columns.Add(col4);
            _focusedDataGrid.Columns.Add(col5);
            _focusedDataGrid.Columns.Add(col6);
            _focusedDataGrid.Columns.Add(col7);

            _focusedDataGrid.IsReadOnly = true;
        }

        /// <summary>
        /// The orderQuery that will depend on the user selection
        /// </summary>
        /// <returns>An OrderQuery object containing the </returns>
        private OrderQuery SimpleSearchOrderQuery() // UNIT TEST
        {
            OrderQuery oq = new OrderQuery();

            string search = KeywordBox.Text;
            oq.Page = currentPage;

            string input1 = numPageBox.Text;
            Match match1 = Regex.Match(input1, @"^[0-9]+$"); //matches only numbers
            if (match1.Success && Convert.ToInt32(numPageBox.Text) <= 50) oq.ResPerPage = Convert.ToInt32(numPageBox.Text);
            else
            {
                MessageBox.Show("Number of results per page must be a number 50 or less.");
                numPageBox.Text = "50";
                oq.ResPerPage = 50;
            }
                        
            if (CheckMultiBox.IsChecked.Value) oq.Multibox = true;
            if (CheckBoxed.IsChecked.Value) oq.Boxed = true;
            if (CheckCancelled.IsChecked.Value) oq.Cancelled = true;
            if (CheckComplete.IsChecked.Value) oq.Complete = true;
            
            if (KeywordTypeFilter.SelectedIndex == -1) //Default - If user does not constrain search
            {
                oq.ShipName = search;//default
            }
            else if (KeywordTypeFilter.SelectedIndex == 0) //user searches by Shipping Name
            {
                oq.ShipName = search;
            }
            else if (KeywordTypeFilter.SelectedIndex == 1) //Search by Billing name
            {
                oq.BillName = search;
            }
            else if (KeywordTypeFilter.SelectedIndex == 2)//Search by Phone Number
            {                
                oq.Phone = search;
            }

            else if (KeywordTypeFilter.SelectedIndex == 3)//search by Order Number
            {
                string input = KeywordBox.Text;
                Match match = Regex.Match(input, @"^[0-9]+$");
                if (match.Success)
                {
                    try
                    {
                        oq.OrderNumber = Convert.ToInt32(search);
                    }
                    catch (OverflowException e)
                    {
                        KeywordBox.Clear();
                        MessageBox.Show("Please Rescan");
                    }
                }
                else
                {
                    MessageBox.Show("Order Number must contain only numbers.");
                    return null;
                }
            }
            else if (KeywordTypeFilter.SelectedIndex == 4)//Package Number
            {
                string input = KeywordBox.Text;
                Match match = Regex.Match(input, @"^[0-9]+$");
                if (match.Success)
                {
                    try
                    {
                        oq.PackageNumber = Convert.ToInt32(search);
                    }
                    catch (OverflowException e)
                    {
                        KeywordBox.Clear();
                        MessageBox.Show("Please Rescan");
                    }
                }
                else
                {
                    MessageBox.Show("Package Number must contain only numbers.");
                    return null;
                }
            }

            //Date Values
            List<DateGroup> date_list = new List<DateGroup>();
            bool search_dates = true;
            foreach (DateGroup dg in dates)
            {
                //Determine if both dates have been set
                if (!((dg.StartDate == DateTime.MinValue && dg.EndDate != DateTime.MinValue) || (dg.StartDate != DateTime.MinValue && dg.EndDate == DateTime.MinValue)))
                {
                    if (dg.StartDate != DateTime.MinValue && dg.EndDate != DateTime.MinValue) date_list.Add(dg);
                }
                else
                {
                    System.Windows.MessageBox.Show("To search with a date range, you must specify a Start and End date.");
                    search_dates = false;
                    break;
                }
            }
            if (search_dates) oq.Dates = date_list.ToArray();

            return oq;
        }

        /// <summary>
        /// This method takes the dates from the date pickers and updates the dates array
        /// </summary>
        private void SyncDates()
        {
            if (OrderProcessStartDate.SelectedDate != null) dates[(int)DateType.ORDER_PROCESS].StartDate = (DateTime)OrderProcessStartDate.SelectedDate;
            if (OrderProcessEndDate.SelectedDate != null) dates[(int)DateType.ORDER_PROCESS].EndDate = (DateTime)OrderProcessEndDate.SelectedDate;
            if (OrderTransactionStartDate.SelectedDate != null) dates[(int)DateType.ORDER_TRANSACTION].StartDate = (DateTime)OrderTransactionStartDate.SelectedDate;
            if (OrderTransactionEndDate.SelectedDate != null) dates[(int)DateType.ORDER_TRANSACTION].EndDate = (DateTime)OrderTransactionEndDate.SelectedDate;
            if (OrderCreationStartDate.SelectedDate != null) dates[(int)DateType.ORDER_CREATION].StartDate = (DateTime)OrderCreationStartDate.SelectedDate;
            if (OrderCreationEndDate.SelectedDate != null) dates[(int)DateType.ORDER_CREATION].EndDate = (DateTime)OrderCreationEndDate.SelectedDate;
            if (PackagePickUpStartDate.SelectedDate != null) dates[(int)DateType.PACKAGE_PICKUP].StartDate = (DateTime)PackagePickUpStartDate.SelectedDate;
            if (PackagePickUpEndDate.SelectedDate != null) dates[(int)DateType.PACKAGE_PICKUP].EndDate = (DateTime)PackagePickUpEndDate.SelectedDate;
            if (PackageBoxedStartDate.SelectedDate != null) dates[(int)DateType.PACKAGE_BOXED].StartDate = (DateTime)PackageBoxedStartDate.SelectedDate;
            if (PackageBoxedEndDate.SelectedDate != null) dates[(int)DateType.PACKAGE_BOXED].EndDate = (DateTime)PackageBoxedEndDate.SelectedDate;
        }

        /// <summary>
        /// Performs search query in a new tab and the new tab becomes the active one
        /// </summary>
        private void ExecuteSearchNewTab_Click(object sender, RoutedEventArgs e)
        {
            currentPage = 1;
            tabpages.Add(currentPage);            

            PageIndex0.Content = " ";
            PageIndex1.Content = " ";
            CurrentPage.Text = currentPage.ToString();
            PageIndex2.Content = currentPage + 1;
            PageIndex3.Content = currentPage + 2;

            PageLeft.IsEnabled = false;

            CloseableTabItem newItem = new CloseableTabItem();
            if (KeywordBox.Text == "") newItem.Header = "New Search";
            else newItem.Header = KeywordBox.Text;
            Dispatcher.BeginInvoke(new Action(() => { newItem.Focus(); }));
            OrderTabControl.Items.Add(newItem);
            System.Windows.Controls.DataGrid dg = new System.Windows.Controls.DataGrid();
            dg.AlternatingRowBackground = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xEC, 0xA7));
            dg.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xCB, 0x7A));
            newItem.Content = dg;
            _focusedTabItem = newItem;
            _focusedDataGrid = (System.Windows.Controls.DataGrid)newItem.Content;
            _focusedDataGrid.MouseDoubleClick += OrderDataGrid1_MouseDoubleClick;
            _focusedDataGrid.RowHeight = 25;

            SyncDates();
            OrderQuery oq = SimpleSearchOrderQuery();
            for (int i = 0; i < dates.Length; i++)
            {
                dates[i] = new DateGroup();
                dates[i].DateType = (DateType)i;
            }
            queries.Add(oq);
            currentQuery = queries[queries.Count - 1];
            Order[] ord = null;
            if (oq != null) ord = ServiceClient.GetOrders(oq);
            else return;

            if (ord == null || ord.Length == 0 || ord[0].OrderBillingName == null || ord[0].OrderCreationDate == DateTime.MinValue)
            {
                System.Windows.MessageBox.Show("There are no orders to display.");
                DataGrid dgd = (DataGrid)_focusedTabItem.Content;
                dgd.Items.Clear();
                return;
            }

            orders.Add(ord);
            
            _populateDataGrid(ord);
        }

        /// <summary>
        /// Displays orders that are older than 30 days
        /// </summary>
        /// <remarks>
        /// Service Dates are still broken, so this is broken as well.
        /// </remarks>
        private void Greater30_Click(object sender, RoutedEventArgs e)
        {
            currentPage = 1;
            tabpages.Add(currentPage);

            PackageBoxedStartDate.SelectedDate = null;
            PackageBoxedStartDate.SelectedDate = DateTime.MinValue.AddYears(2000);
            PackageBoxedEndDate.SelectedDate = null;
            PackageBoxedEndDate.SelectedDate = DateTime.Today.AddDays(-30);

            SyncDates();
            OrderQuery oq = SimpleSearchOrderQuery();
            for (int i = 0; i < dates.Length; i++)
            {
                dates[i] = new DateGroup();
                dates[i].DateType = (DateType)i;
            }
            queries.Add(oq);
            currentQuery = queries[queries.Count - 1];
            Order[] ord = null;
            if (oq != null) ord = ServiceClient.GetOrders(oq);
            else return;

            if (ord == null || ord.Length == 0 || ord[0].OrderBillingName == null || ord[0].OrderCreationDate == DateTime.MinValue)
            {
                System.Windows.MessageBox.Show("There are no orders to display.");
                DataGrid dgrd = (DataGrid)_focusedTabItem.Content;
                dgrd.Items.Clear();
                return;
            }

            orders.Add(ord);

            CloseableTabItem newItem = new CloseableTabItem();
            Dispatcher.BeginInvoke(new Action(() => { newItem.Focus(); }));
            OrderTabControl.Items.Add(newItem);
            System.Windows.Controls.DataGrid dgd = new System.Windows.Controls.DataGrid();
            dgd.AlternatingRowBackground = new SolidColorBrush(Color.FromArgb(0xFF,0xFF,0xEC,0xA7));
            dgd.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0xCB, 0x7A));
            newItem.Content = dgd;
            _focusedTabItem = newItem;
            _focusedDataGrid = (System.Windows.Controls.DataGrid)newItem.Content;
            _focusedDataGrid.MouseDoubleClick += OrderDataGrid1_MouseDoubleClick;
            _focusedDataGrid.RowHeight = 25;
                   
            _populateDataGrid(ord);

            _focusedTabItem.Header = "Boxed >30 days";
                              
            //ReInitialize the DateGroup Array
            for (int i = 0; i < dates.Length; i++)
            {
                dates[i] = new DateGroup();
                dates[i].DateType = (DateType)i;
            }
            ClearDates();
        }

        /// <summary> {Region Selected Changed Event Handlers}
        /// Whenever one of the dates changes, the corresponding event is fired and that date is changed in the dates array.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        #region Selected Date Changed Event Handlers

        private void OrderProcessStartDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (OrderProcessStartDate.SelectedDate != null) dates[(int)DateType.ORDER_PROCESS].StartDate = (DateTime)OrderProcessStartDate.SelectedDate;
            else dates[(int)DateType.ORDER_PROCESS].StartDate = DateTime.MinValue;
        }

        private void OrderProcessEndDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (OrderProcessEndDate.SelectedDate != null) dates[(int)DateType.ORDER_PROCESS].EndDate = (DateTime)OrderProcessEndDate.SelectedDate;
            else dates[(int)DateType.ORDER_PROCESS].EndDate = DateTime.MinValue;
        }

        private void OrderCreationStartDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (OrderCreationStartDate.SelectedDate != null) dates[(int)DateType.ORDER_CREATION].StartDate = (DateTime)OrderCreationStartDate.SelectedDate;
            else dates[(int)DateType.ORDER_CREATION].StartDate = DateTime.MinValue;
        }

        private void OrderCreationEndDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (OrderCreationEndDate.SelectedDate != null) dates[(int)DateType.ORDER_CREATION].EndDate = (DateTime)OrderCreationEndDate.SelectedDate;
            else dates[(int)DateType.ORDER_CREATION].EndDate = DateTime.MinValue;
        }

        private void OrderTransactionStartDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (OrderTransactionStartDate.SelectedDate != null) dates[(int)DateType.ORDER_TRANSACTION].StartDate = (DateTime)OrderTransactionStartDate.SelectedDate;
            else dates[(int)DateType.ORDER_TRANSACTION].StartDate = DateTime.MinValue;
        }

        private void OrderTransactionEndDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (OrderTransactionEndDate.SelectedDate != null) dates[(int)DateType.ORDER_TRANSACTION].EndDate = (DateTime)OrderTransactionEndDate.SelectedDate;
            else dates[(int)DateType.ORDER_TRANSACTION].EndDate = DateTime.MinValue;
        }

        private void PackageBoxedStartDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PackageBoxedStartDate.SelectedDate != null) dates[(int)DateType.PACKAGE_BOXED].StartDate = (DateTime)PackageBoxedStartDate.SelectedDate;
            else dates[(int)DateType.PACKAGE_BOXED].StartDate = DateTime.MinValue;
        }

        private void PackageBoxedEndDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PackageBoxedEndDate.SelectedDate != null) dates[(int)DateType.PACKAGE_BOXED].EndDate = (DateTime)PackageBoxedEndDate.SelectedDate;
            else dates[(int)DateType.PACKAGE_BOXED].EndDate = DateTime.MinValue;
        }

        private void PackagePickUpStartDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PackagePickUpStartDate.SelectedDate != null) dates[(int)DateType.PACKAGE_PICKUP].StartDate = (DateTime)PackagePickUpStartDate.SelectedDate;
            else dates[(int)DateType.PACKAGE_PICKUP].StartDate = DateTime.MinValue;
        }

        private void PackagePickUpEndDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PackagePickUpEndDate.SelectedDate != null) dates[(int)DateType.PACKAGE_PICKUP].EndDate = (DateTime)PackagePickUpEndDate.SelectedDate;
            else dates[(int)DateType.PACKAGE_PICKUP].EndDate = DateTime.MinValue;
        }

        #endregion
        
        /// <summary>
        /// Event handler for the tab change event. The primary goal is to set the search controls to the settings that were originally searched for.
        /// </summary>
        private void OrderTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ClearDates();
            _focusedTabItem = (CloseableTabItem)OrderTabControl.SelectedItem;
            if (_focusedTabItem == null) _focusedTabItem = (CloseableTabItem)OrderTabControl.Items[0];            
            _focusedDataGrid = (System.Windows.Controls.DataGrid)_focusedTabItem.Content;

            currentPage = tabpages[OrderTabControl.Items.IndexOf(_focusedTabItem)];            
            if (currentPage == 2)
            {
                PageIndex0.Content = " ";
                PageIndex1.Content = currentPage - 1;
                CurrentPage.Text = currentPage.ToString();
                PageIndex2.Content = currentPage + 1;
                PageIndex3.Content = currentPage + 2;
                PageLeft.IsEnabled = true;
            }
            else if (currentPage == 1)
            {
                PageIndex0.Content = " ";
                PageIndex1.Content = " ";
                CurrentPage.Text = currentPage.ToString();
                PageIndex2.Content = currentPage + 1;
                PageIndex3.Content = currentPage + 2;
                PageLeft.IsEnabled = false;
            }
            else
            {
                PageIndex0.Content = currentPage - 2;
                PageIndex1.Content = currentPage - 1;
                CurrentPage.Text = currentPage.ToString();
                PageIndex2.Content = currentPage + 1;
                PageIndex3.Content = currentPage + 2;
                PageLeft.IsEnabled = true;
            }

            currentQuery = queries[OrderTabControl.Items.IndexOf(_focusedTabItem)];

            if (currentQuery.BillName != null/* && currentQuery.BillName != ""*/)
            {
                KeywordBox.Text = currentQuery.BillName;
                KeywordTypeFilter.SelectedIndex = 1;
            }
            else if (currentQuery.ShipName != null/* && currentQuery.ShipName != ""*/) 
            {
                KeywordBox.Text = currentQuery.ShipName;
                KeywordTypeFilter.SelectedIndex = 0;
            }
            else if (currentQuery.PackageNumber != 0)
            {
                KeywordBox.Text = currentQuery.PackageNumber.ToString();
                KeywordTypeFilter.SelectedIndex = 4;
            }
            else if (currentQuery.OrderNumber != 0)
            {
                KeywordBox.Text = currentQuery.OrderNumber.ToString();
                KeywordTypeFilter.SelectedIndex = 3;
            }
            else if (currentQuery.Phone != null && currentQuery.Phone != "")
            {
                KeywordBox.Text = currentQuery.Phone;
                KeywordTypeFilter.SelectedIndex = 2;
            }

            if (currentQuery.Complete != null && currentQuery.Complete.Value) CheckComplete.IsChecked = true;
            else if (currentQuery.Complete == null) CheckComplete.IsChecked = false;
            if (currentQuery.Cancelled != null && currentQuery.Cancelled.Value) CheckCancelled.IsChecked = true;
            else if (currentQuery.Cancelled == null) CheckCancelled.IsChecked = false;
            if (currentQuery.Multibox != null && currentQuery.Multibox.Value) CheckMultiBox.IsChecked = true;
            else if (currentQuery.Multibox == null) CheckMultiBox.IsChecked = false;
            if (currentQuery.Boxed != null && currentQuery.Boxed.Value) CheckBoxed.IsChecked = true;
            else if (currentQuery.Boxed == null) CheckBoxed.IsChecked = false;

            if (currentQuery.Dates.Length > 0 && currentQuery.Dates != null)
            {
                for (int i = 0; i < currentQuery.Dates.Length; i++)
                {
                    if (currentQuery.Dates[i].DateType == DateType.ORDER_CREATION)
                    {
                        dates[(int)DateType.ORDER_CREATION].StartDate = currentQuery.Dates[i].StartDate;
                        dates[(int)DateType.ORDER_CREATION].EndDate = currentQuery.Dates[i].EndDate;
                        OrderCreationStartDate.SelectedDate = currentQuery.Dates[i].StartDate;
                        OrderCreationEndDate.SelectedDate = currentQuery.Dates[i].EndDate;
                    }
                    else if (currentQuery.Dates[i].DateType == DateType.ORDER_PROCESS)
                    {
                        dates[(int)DateType.ORDER_PROCESS].StartDate = currentQuery.Dates[i].StartDate;
                        dates[(int)DateType.ORDER_PROCESS].EndDate = currentQuery.Dates[i].EndDate;
                        OrderProcessStartDate.SelectedDate = currentQuery.Dates[i].StartDate;
                        OrderProcessEndDate.SelectedDate = currentQuery.Dates[i].EndDate;
                    }
                    else if (currentQuery.Dates[i].DateType == DateType.ORDER_TRANSACTION)
                    {
                        dates[(int)DateType.ORDER_TRANSACTION].StartDate = currentQuery.Dates[i].StartDate;
                        dates[(int)DateType.ORDER_TRANSACTION].EndDate = currentQuery.Dates[i].EndDate;
                        OrderTransactionStartDate.SelectedDate = currentQuery.Dates[i].StartDate;
                        OrderTransactionEndDate.SelectedDate = currentQuery.Dates[i].EndDate;
                    }
                    else if (currentQuery.Dates[i].DateType == DateType.PACKAGE_BOXED)
                    {
                        dates[(int)DateType.PACKAGE_BOXED].StartDate = currentQuery.Dates[i].StartDate;
                        dates[(int)DateType.PACKAGE_BOXED].EndDate = currentQuery.Dates[i].EndDate;
                        PackageBoxedStartDate.SelectedDate = currentQuery.Dates[i].StartDate;
                        PackageBoxedEndDate.SelectedDate = currentQuery.Dates[i].EndDate;
                    }
                    else
                    {
                        dates[(int)DateType.PACKAGE_PICKUP].StartDate = currentQuery.Dates[i].StartDate;
                        dates[(int)DateType.PACKAGE_PICKUP].EndDate = currentQuery.Dates[i].EndDate;
                        PackagePickUpStartDate.SelectedDate = currentQuery.Dates[i].StartDate;
                        PackagePickUpEndDate.SelectedDate = currentQuery.Dates[i].EndDate;
                    }
                }
            }
        }

        /// <summary>
        /// The button funtion exits the window
        /// </summary>
        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Calls the service with the same query while incrementing the page number
        /// </summary>
        /// <param name="sender">sending object</param>
        /// <param name="e">event arguments</param>
        private void PageLeft_Click(object sender, RoutedEventArgs e)
        {
            currentPage--;
            tabpages[this.OrderTabControl.Items.IndexOf(_focusedTabItem)] = currentPage;
            if (currentPage == 1) PageLeft.IsEnabled = false;

            OrderQuery oq = SimpleSearchOrderQuery();
            queries[OrderTabControl.Items.IndexOf(_focusedTabItem)] = oq;
            Order[] ord = null;
            if (oq != null) ord = ServiceClient.GetOrders(oq);
            else return;
            if (ord == null || ord.Length == 0)
            {
                System.Windows.MessageBox.Show("There are no orders to display.");
                currentPage++;
                oq = SimpleSearchOrderQuery();
                if (oq != null) ord = ServiceClient.GetOrders(oq);
                else return;
            }

            orders.Add(ord);

            _populateDataGrid(ord);

            //UNIT TEST
            if (currentPage == 2)
            {
                PageIndex0.Content = " ";
                PageIndex1.Content = currentPage - 1;
                CurrentPage.Text = currentPage.ToString();
                PageIndex2.Content = currentPage + 1;
                PageIndex3.Content = currentPage + 2;
            }
            else if (currentPage == 1)
            {
                PageIndex0.Content = " ";
                PageIndex1.Content = " ";
                CurrentPage.Text = currentPage.ToString();
                PageIndex2.Content = currentPage + 1;
                PageIndex3.Content = currentPage + 2;
            }
            else
            {
                PageIndex0.Content = currentPage - 2;
                PageIndex1.Content = currentPage - 1;
                CurrentPage.Text = currentPage.ToString();
                PageIndex2.Content = currentPage + 1;
                PageIndex3.Content = currentPage + 2;
            }

        }

        /// <summary>
        /// Calls the service with the same query while decrementing the page number.
        /// </summary>
        /// <param name="sender">sending object</param>
        /// <param name="e">event arguments</param>
        private void PageRight_Click(object sender, RoutedEventArgs e)
        {
            currentPage++;
            tabpages[this.OrderTabControl.Items.IndexOf(_focusedTabItem)] = currentPage;
            PageLeft.IsEnabled = true;

            OrderQuery oq = SimpleSearchOrderQuery();
            queries[OrderTabControl.Items.IndexOf(_focusedTabItem)] = oq;
            Order[] ord = null;
            if (oq != null) ord = ServiceClient.GetOrders(oq);
            else return;
            if (ord == null || ord.Length == 0)
            {
                System.Windows.MessageBox.Show("There are no orders to display.");
                currentPage--;
                oq = SimpleSearchOrderQuery();
                if (oq != null) ord = ServiceClient.GetOrders(oq);
                else return;
            }

            orders.Add(ord);

            _populateDataGrid(ord);

            if (currentPage == 2)
            {
                PageIndex0.Content = " ";
                PageIndex1.Content = currentPage - 1;
                CurrentPage.Text = currentPage.ToString();
                PageIndex2.Content = currentPage + 1;
                PageIndex3.Content = currentPage + 2;
            }
            else if (currentPage == 1)
            {
                PageLeft.IsEnabled = false;
                PageIndex0.Content = " ";
                PageIndex1.Content = " ";
                CurrentPage.Text = currentPage.ToString();
                PageIndex2.Content = currentPage + 1;
                PageIndex3.Content = currentPage + 2;
            }
            else
            {
                PageIndex0.Content = currentPage - 2;
                PageIndex1.Content = currentPage - 1;
                CurrentPage.Text = currentPage.ToString();
                PageIndex2.Content = currentPage + 1;
                PageIndex3.Content = currentPage + 2;
            }
        }

        private void ExitMenu_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Handles the event when a key is pressed in the page number box.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CurrentPage_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (CurrentPage.Text != "" && KeywordBox != null && e.Key == Key.Enter)
            {
                currentPage = Convert.ToInt32(CurrentPage.Text);
                tabpages[this.OrderTabControl.Items.IndexOf(_focusedTabItem)] = currentPage;
                PageLeft.IsEnabled = true;

                OrderQuery oq = SimpleSearchOrderQuery();
                queries[OrderTabControl.Items.IndexOf(_focusedTabItem)] = oq;
                Order[] ord = null;
                if (oq != null) ord = ServiceClient.GetOrders(oq);
                else return;

                if (ord == null || ord.Length == 0)
                {
                    System.Windows.MessageBox.Show("There are no orders to display.");
                    currentPage = 1;
                    if (oq != null) ord = ServiceClient.GetOrders(oq);
                    else return;
                    ord = ServiceClient.GetOrders(oq);
                }

                orders.Add(ord);

                _populateDataGrid(ord);

                if (currentPage == 2)
                {
                    PageIndex0.Content = " ";
                    PageIndex1.Content = currentPage - 1;
                    CurrentPage.Text = currentPage.ToString();
                    PageIndex2.Content = currentPage + 1;
                    PageIndex3.Content = currentPage + 2;
                }
                else if (currentPage == 1)
                {
                    PageLeft.IsEnabled = false;
                    PageIndex0.Content = " ";
                    PageIndex1.Content = " ";
                    CurrentPage.Text = currentPage.ToString();
                    PageIndex2.Content = currentPage + 1;
                    PageIndex3.Content = currentPage + 2;
                }
                else
                {
                    PageIndex0.Content = currentPage - 2;
                    PageIndex1.Content = currentPage - 1;
                    CurrentPage.Text = currentPage.ToString();
                    PageIndex2.Content = currentPage + 1;
                    PageIndex3.Content = currentPage + 2;
                }
            }
        }

        /// <summary>
        /// Event handler for the search filter box. the primary goal of the method is to
        /// change the combo box to the appropriate setting based on the length of the input.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void KeywordBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            string input = KeywordBox.Text;
            Match match = Regex.Match(input, @"^[0-9\n]+$");
            if (match.Success)
            {
                if (KeywordBox.Text.Length == 5 || KeywordBox.Text.Length == 6)
                {
                    KeywordTypeFilter.SelectedIndex = 4;
                }
                else if (KeywordBox.Text.Length == 9)
                {
                    KeywordTypeFilter.SelectedIndex = 3;
                }
            }
        }

        private void PrinterMenu_Click(object sender, RoutedEventArgs e)
        {
            PrintSettingsWindow psw = new PrintSettingsWindow();
            psw.Show();
        }

        private void ClearForm_Click(object sender, RoutedEventArgs e)
        {
            KeywordBox.Clear();
            for (int i = 0; i < dates.Length; i++)
            {
                dates[i] = new DateGroup();
                dates[i].DateType = (DateType)i;
            }
            ClearDates();
        }

        private void ClearMenu_Click(object sender, RoutedEventArgs e)
        {
            BatchClearWindow bcw = new BatchClearWindow();
            bcw.Show();
        }

        private void CredMenu_Click(object sender, RoutedEventArgs e)
        {
            CredWindow cw = new CredWindow();
            cw.Show();
        }
    }

    /// <summary>
    /// Class describes the design and behaviours of customized closing capabilities of tabs
    /// </summary>
    #region CloseableTabItem Class

    public class CloseableTabItem : TabItem
    {
        static CloseableTabItem()
        {
            //This OverrideMetadata call tells the system that this element wants to provide a style that is different than its base class.
            //This style is defined in themes\generic.xaml
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CloseableTabItem),
                new FrameworkPropertyMetadata(typeof(CloseableTabItem)));
        }

        public static readonly RoutedEvent CloseTabEvent = EventManager.RegisterRoutedEvent("CloseTab", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(CloseableTabItem));

        public event RoutedEventHandler CloseTab
        {
            add { AddHandler(CloseTabEvent, value); }
            remove { RemoveHandler(CloseTabEvent, value); }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            System.Windows.Controls.Button closeButton = base.GetTemplateChild("PART_Close") as System.Windows.Controls.Button;
            if (closeButton != null)
                closeButton.Click += new System.Windows.RoutedEventHandler(closeButton_Click);
        }

        void closeButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.RaiseEvent(new RoutedEventArgs(CloseTabEvent, this));
        }
    }

    #endregion
}
